package xin.marcher.module.rights.service.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.marcher.module.common.core.JsonResult;
import xin.marcher.module.rights.domain.dto.PermissionDTO;
import xin.marcher.module.rights.domain.dto.RolePermissionRelationDTO;
import xin.marcher.module.rights.domain.request.PermissionRequest;
import xin.marcher.module.rights.domain.request.QueryPermissionRequest;
import xin.marcher.module.rights.domain.request.RemovePermissionRequest;
import xin.marcher.module.rights.repository.RightsRepository;
import xin.marcher.module.rights.service.PermissionService;

import java.util.List;
import java.util.Objects;

/**
 *
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private RightsRepository rightsRepository;

    @Override
    public JsonResult savePermission(PermissionRequest request) {
        // 校验角色编码
        PermissionDTO permissionDTO = rightsRepository.queryPermissionByPermissionCode(request.getPermissionCode());
        if (Objects.nonNull(permissionDTO)) {
            return JsonResult.buildError("权限编码已存在");
        }
        rightsRepository.savePermission(request);
        return JsonResult.buildSuccess();
    }

    @Override
    public JsonResult removePermission(RemovePermissionRequest request) {
        // 校验权限是不是已经分配角色了
        List<RolePermissionRelationDTO> rolePermissionRelationDTOS = rightsRepository
                .queryRolePermissionRelationByPermissionId(request.getPermissionId());
        if (CollectionUtils.isNotEmpty(rolePermissionRelationDTOS)) {
            return JsonResult.buildError("权限已经分配给了角色无法删除");
        }
        // 校验改权限是否有子权限(权限的父子关系只是描述菜单和按钮之间的层级关系，此层级关系不作为影响授权的因素)
        List<PermissionDTO> permissionDTOS = rightsRepository.queryPermissionByParentId(request.getPermissionId());
        if (CollectionUtils.isNotEmpty(permissionDTOS)) {
            return JsonResult.buildError("该权限下有子权限无法删除");
        }
        // 删除权限
        rightsRepository.removePermission(request);
        return JsonResult.buildSuccess();
    }

    @Override
    public List<PermissionDTO> queryPermission(QueryPermissionRequest request) {
        return rightsRepository.queryPermission(request);
    }
}
